package org.stream.answerduel.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.stream.answerduel.entity.AnswerDetails;
import org.stream.answerduel.repository.AnswerDetailsRepository;
import org.stream.answerduel.util.SnowflakeIdWorker;
import org.stream.answerduel.vo.AnswerDetailsVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 功能描述：
 *
 * @Auther: 苏建誉
 * @Date: 2019/7/17 22:12
 */
@Service
@Slf4j
public class AnswerDetailsService {
    private static AnswerDetailsService instance=null;
    @Autowired
    private SubjectService subjectService;

    @Autowired
    private AnswerDetailsRepository answerDetailsRepository;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @PostConstruct
    public void Init(){
        if(instance==null){
            instance=this;
        }
    }

    public static AnswerDetailsService getInstance() {
        if(instance==null){
            instance=new AnswerDetailsService();
        }
        return instance;
    }
    /**
     * 功能描述：
     *
     * @param aDVo 对战信息
     */
    public void add(AnswerDetailsVo aDVo) {
        AnswerDetails aD = new AnswerDetails();
        BeanUtils.copyProperties(aDVo, aD);
        Long id=snowflakeIdWorker.nextId();
        aD.setId(id);
        aD.setCreateBy(aD.getUserId());
        aD.setCreateAt(new Date());
        aD.setUpdateBy(aD.getUserId());
        aD.setUpdateAt(new Date());
        answerDetailsRepository.save(aD);
    }

    /**
     * 功能描述：
     *
     * @param id 用户历史记录id
     * @param pageNum 当前页码
     * @param pageSize 当前页大小
     */
    public Page<AnswerDetailsVo> findAnswerDetailsById(Long id,int pageNum,int pageSize) {

        Page<AnswerDetails> tmp=answerDetailsRepository.findByUserId(id, PageRequest.of(pageNum,pageSize));
        List<AnswerDetailsVo> list=new ArrayList<AnswerDetailsVo>();
        for (AnswerDetails x:tmp){
            AnswerDetailsVo aDV= new AnswerDetailsVo();
            BeanUtils.copyProperties(x, aDV);
            aDV.setSubjectVo(subjectService.getSubjectBySubjectId(aDV.getSubjectId()));
            list.add(aDV);
        }
        return new PageImpl<AnswerDetailsVo>(list);
    }
}
